﻿using HalconDotNet;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeaderCCSLaserUI.Models.VisionModels
{
    public class VM_BlobCircle : FunctionBase
    {
        public override bool Run(ref HObject ho_Image, string paramJson, ref HTuple hv_Row, ref HTuple hv_Column, ref HTuple hv_Angle, ref HTuple hv_Score, ref HObject maxRegion, ref HObject ho_SelectedRegion, ref HTuple v1, ref HTuple v2)
        {
            try
            {
                var MBlobCircleParam = JsonConvert.DeserializeObject<BlobCircleParam>(paramJson);
                hv_Angle = new HTuple(0);
                HOperatorSet.GenCircle(out var ho_Circle, hv_Row, hv_Column, MBlobCircleParam.Radius);
                HOperatorSet.ReduceDomain(ho_Image, ho_Circle, out var ho_ImageReduced);
                HOperatorSet.Threshold(ho_ImageReduced, out var ho_Region, MBlobCircleParam.MinGray, MBlobCircleParam.MaxGray);
                HOperatorSet.FillUp(ho_Region, out var ho_RegionFillUp);
                HOperatorSet.OpeningCircle(ho_RegionFillUp, out var ho_RegionOpening, MBlobCircleParam.OpeningRadius);
                HOperatorSet.Connection(ho_RegionOpening, out var ho_ConnectedRegions);
                HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SelectedRegion, ((new HTuple("area")).TupleConcat(
                     "ra")).TupleConcat("rb"), "and", ((new HTuple(MBlobCircleParam.SelectAreaMin)).TupleConcat(MBlobCircleParam.SelectRadiusMin)).TupleConcat(
                     MBlobCircleParam.SelectRadiusMin), ((new HTuple(MBlobCircleParam.SelectAreaMax)).TupleConcat(MBlobCircleParam.SelectRadiusMax)).TupleConcat(MBlobCircleParam.SelectRadiusMax));
                HOperatorSet.CountObj(ho_SelectedRegion, out var hv_Number);
                if ((int)(new HTuple(hv_Number.TupleEqual(1))) != 0)
                {
                    HOperatorSet.RegionFeatures(ho_SelectedRegion, "row", out hv_Row);
                    HOperatorSet.RegionFeatures(ho_SelectedRegion, "column", out hv_Column);
                }
                else
                {
                    HOperatorSet.RegionFeatures(ho_ConnectedRegions, "area", out var hv_Area);
                    var areaMax = hv_Area.TupleMax();
                    HOperatorSet.SelectShape(ho_ConnectedRegions, out maxRegion, new HTuple("area"), "and", areaMax, areaMax);
                }
                ho_Circle.Dispose();
                ho_ImageReduced.Dispose();
                ho_Region.Dispose();
                ho_RegionFillUp.Dispose();
                ho_RegionOpening.Dispose();
                ho_ConnectedRegions.Dispose();
                return true;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return false;
            }

        }
    }
}
